package com.smart.village.big.screen.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.smart.village.big.screen.domain.*;
import com.smart.village.big.screen.mapper.*;
import com.smart.village.big.screen.service.NewsService;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public  class NewsServiceImpl implements NewsService {
    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private NewsTagsMapper newsTagsMapper;
    @Autowired
    private NewsCategoryMapper newsCategoryMapper;
    @Autowired
    private VideosMapper videosMapper;
    @Autowired
    private PartyOrganizationMapper partyOrganizationMapper;
    @Autowired
    private StudyFilesMapper studyFilesMapper;
    @Autowired
    private CommentsMapper commentsMapper;

    @Override
    public News selectByPrimaryKey(String id) {
        News news = newsMapper.selectByPrimaryKey(id);
        String newsViewsCount = news.getNewsViewsCount();
        int i;
        if (StringUtils.isNotBlank(newsViewsCount)) {
            i = Integer.parseInt(newsViewsCount);
            i += 1;
        } else {
            newsViewsCount = "0";
            i = Integer.parseInt(newsViewsCount);
            i += 1;
        }
        news.setNewsViewsCount(String.valueOf(i));
        newsMapper.updateNewsViewsCount(news);
        return news;
    }

    @Override
    public List<JSONObject> getList(String newsCategorySerialNumber,String partyOrganizationActivitySerialNumber, int pageNum, int pageSize, String search,int environment,String NewsTerminal) {
        List<JSONObject> resultList = Lists.newArrayList();

        // 如果没有传固定的分类id 则获取所有的分类的子节点
        if (StringUtils.isBlank(newsCategorySerialNumber)) {
            List<NewsCategory> oneLevelCategory = newsCategoryMapper.getOneLevelCategory(NewsTerminal);
            oneLevelCategory.forEach(newsCategory -> {
                List<String> treeList = Lists.newArrayList();
                treeList.add(newsCategory.getNewsCategorySerialNumber());
                List<NewsCategory> treeListByParentSerialNumber = newsCategoryMapper.selectTreeListByParentSerialNumber(newsCategory.getNewsCategorySerialNumber(),NewsTerminal);
                if (!ObjectUtils.isEmpty(treeListByParentSerialNumber)) {
                    treeListByParentSerialNumber.forEach(nc -> {
                        treeList.add(nc.getNewsCategorySerialNumber());
                    });
                }
                PageHelper.startPage(pageNum, pageSize);
                // environment 0 大屏 1 小程序
                List<NewsVo> newsVos = newsMapper.selectNewsVoListInCategorySerialNumberList(treeList,partyOrganizationActivitySerialNumber, search,environment,NewsTerminal);
                PageInfo<NewsVo> pageInfo = new PageInfo<>(newsVos);
                if(!CollectionUtils.isEmpty(newsVos)) {
                    execFormatSubTitle(newsVos);
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("category", newsCategory);
                jsonObject.put("news", pageInfo.getList());
                jsonObject.put("total", pageInfo.getTotal());
                resultList.add(jsonObject);
            });
        }
        // 如果传了固定的分类id 则获取该分类下的所有子节点
        else {
            NewsCategory newsCategory = newsCategoryMapper.selectBySerialNumber(newsCategorySerialNumber);
            if (!ObjectUtils.isEmpty(newsCategory)) {
                List<String> treeList = Lists.newArrayList();
                treeList.add(newsCategory.getNewsCategorySerialNumber());
                List<NewsCategory> treeListByParentSerialNumber = newsCategoryMapper.selectTreeListByParentSerialNumber(newsCategorySerialNumber,"");
                if (!ObjectUtils.isEmpty(treeListByParentSerialNumber)) {
                    treeListByParentSerialNumber.forEach(nc -> {
                        treeList.add(nc.getNewsCategorySerialNumber());
                    });
                }
                PageHelper.startPage(pageNum, pageSize);
                List<NewsVo> newsVos = newsMapper.selectNewsVoListInCategorySerialNumberList(treeList, partyOrganizationActivitySerialNumber,search,environment,NewsTerminal);
                PageInfo<NewsVo> pageInfo = new PageInfo<>(newsVos);
                if(!CollectionUtils.isEmpty(newsVos)) {
                    execFormatSubTitle(newsVos);
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("category", newsCategory);
                jsonObject.put("news", pageInfo.getList());
                jsonObject.put("total", pageInfo.getTotal());
                resultList.add(jsonObject);
            }
        }
        return resultList;
    }

    @Override
    public List<NewsVo> getWorkDynamicBannerList(int cnt,int environment,String NewsTerminal) {
        PageHelper.startPage(1, cnt);
        return newsMapper.getWorkDynamicBannerList(environment,NewsTerminal);
    }


    @Override
    public List<JSONObject> getWorkDynamicList(String newsTagSerialNumber, int pageNum, int pageSize, String search,int environment,String NewsTerminal) {
        List<JSONObject> list = new ArrayList<>();
        if (StringUtils.isBlank(newsTagSerialNumber)) {
            List<NewsTags> newsTagsList = newsTagsMapper.getNewsTagsList();
            for (NewsTags newsTags : newsTagsList) {
                PageHelper.startPage(pageNum, pageSize);
                List<NewsVo> workDynamicList = newsMapper.getWorkDynamicList(newsTags.getNewsTagSerialNumber(), search,environment,NewsTerminal);
                PageInfo<NewsVo> pageInfo = new PageInfo<>(workDynamicList);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("tags", newsTags);
                jsonObject.put("news", pageInfo.getList());
                jsonObject.put("total", pageInfo.getTotal());
                execFormatSubTitle(workDynamicList);
                list.add(jsonObject);
            }
        } else {
            NewsTags newsTags = newsTagsMapper.selectByNewsTagSerialNumber(newsTagSerialNumber);
            PageHelper.startPage(pageNum, pageSize);
            List<NewsVo> workDynamicList = newsMapper.getWorkDynamicList(newsTagSerialNumber, search,environment,NewsTerminal);
            PageInfo<NewsVo> pageInfo = new PageInfo<>(workDynamicList);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("tags", newsTags);
            jsonObject.put("news", pageInfo.getList());
            jsonObject.put("total", pageInfo.getTotal());
            execFormatSubTitle(workDynamicList);
            list.add(jsonObject);
        }
        return list;
    }


    private void execFormatSubTitle(List<NewsVo> newsVoList) {
        newsVoList.forEach(newsVo -> {
            String newsSubTitle = newsVo.getNewsSubTitle();
            if(!StringUtils.isEmpty(newsSubTitle)) {
                Document doc = Jsoup.parse(newsSubTitle);

                // 查找第一个<p>标签
                Elements paragraphs = doc.select("p");
                if (paragraphs.size() > 0) {
                    Element firstParagraph = paragraphs.first(); // 获取第一个<p>标签
                    String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                    if (content.length() > 70) {
                        content = content.substring(0, 67) + "...";
                    }
                    newsVo.setNewsSubTitle(content);
                    return;
                } else {
                    Elements h1 = doc.select("h1");
                    Elements h2 = doc.select("h2");
                    Elements h3 = doc.select("h3");
                    Elements h4 = doc.select("h4");
                    Elements h5 = doc.select("h5");
                    Elements ul = doc.select("ul");
                    Elements ol = doc.select("ol");
                    Elements li = doc.select("li");
                    Elements div = doc.select("div");
                    Elements span = doc.select("span");
                    Elements strong = doc.select("strong");
                    if (h1.size() > 0) {
                        Element firstParagraph = h1.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    }
                    if (h2.size() > 0) {
                        Element firstParagraph = h2.first(); // 获取第一个<h2>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    }
                    if (h3.size() > 0) {
                        Element firstParagraph = h3.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    }
                    if (h4.size() > 0) {
                        Element firstParagraph = h4.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    }
                    if (h5.size() > 0) {
                        Element firstParagraph = h5.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    } if (ul.size() > 0) {
                        Element firstParagraph = ul.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    } if (ol.size() > 0) {
                        Element firstParagraph = ol.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    } if (div.size() > 0) {
                        Element firstParagraph = div.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    } if (span.size() > 0) {
                        Element firstParagraph = span.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    } if (strong.size() > 0) {
                        Element firstParagraph = strong.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    } if (li.size() > 0) {
                        Element firstParagraph = li.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    }
                }
            }
        });
    }

    @Override
    public JSONObject getWorkResults(int environment,String NewsTerminal) {
        JSONObject jsonObject = new JSONObject();
        List<NewsTags> newsTagsList = newsTagsMapper.getNewsTagsList();
        List<String> nameList = Lists.newArrayList();
        List<Integer> cntList = Lists.newArrayList();
        for (NewsTags newsTags : newsTagsList) {
            nameList.add(newsTags.getNewsTag());
            List<NewsVo> workDynamicList = newsMapper.getWorkDynamicList(newsTags.getNewsTagSerialNumber(), "",environment,NewsTerminal);
            cntList.add(workDynamicList.size());
        }
        List<String> videoCategoryList = Lists.newArrayList();
        videoCategoryList.add("VC0000000000008");
        videoCategoryList.add("VC0000000000009");
        for (String ca : videoCategoryList) {
            HashMap<String, Object> videosCategory = videosMapper.getVideosCategoryByCategorySerialNumber(ca);
            if (!ObjectUtils.isEmpty(videosCategory)) {
                String videoCategory = videosCategory.get("videoCategory").toString();
                nameList.add(videoCategory);
                List<String> treeList = Lists.newArrayList();
                treeList.add(videosCategory.get("videoCategorySerialNumber").toString());
                List<HashMap<String, Object>> treeListByParentSerialNumber = videosMapper.getVideosCategoryChildIdList(ca);
                if (!ObjectUtils.isEmpty(treeListByParentSerialNumber)) {
                    treeListByParentSerialNumber.forEach(nc -> {
                        treeList.add(nc.get("videoCategorySerialNumber").toString());
                    });
                }
                int cnt = 0;
                for (String cc : treeList) {
                    List<Videos> videosByCategory = videosMapper.getVideosByCategory(cc, "",environment);
                    cnt += videosByCategory.size();
                }
                cntList.add(cnt);
            }
        }

        jsonObject.put("nameList", nameList);
        jsonObject.put("dataList", cntList);
        return jsonObject;
    }

    @Override
    public JSONObject getInformationPublishStatics(String newsCategorySerialNumber,int environment,String NewsTerminal) {
        JSONObject jsonObject = new JSONObject();
        List<String> nameList = Lists.newArrayList();
        List<Integer> cntList = Lists.newArrayList();
        NewsCategory newsCategory = newsCategoryMapper.selectBySerialNumber(newsCategorySerialNumber);
        if (!ObjectUtils.isEmpty(newsCategory)) {
            List<String> treeList = Lists.newArrayList();
            treeList.add(newsCategory.getNewsCategorySerialNumber());
            List<NewsCategory> treeListByParentSerialNumber = newsCategoryMapper.selectTreeListByParentSerialNumber(newsCategorySerialNumber,"");
            if (!ObjectUtils.isEmpty(treeListByParentSerialNumber)) {
                treeListByParentSerialNumber.forEach(nc -> {
                    treeList.add(nc.getNewsCategorySerialNumber());
                });
            }
            //environment 0 大屏 1 小程序
            List<NewsVo> newsVos = newsMapper.selectNewsVoListInCategorySerialNumberList(treeList, "","",environment,NewsTerminal);
            newsVos.forEach(newsVo -> {
                if (StringUtils.isNotEmpty(newsVo.getDataBelongPartyOrganizationSerialNumber())) {
                    JSONObject secondLevelPartyOrganization = partyOrganizationMapper.getSecondLevelPartyOrganizationBySerialNumber(newsVo.getPartyOrganizationSerialNumber());
                    newsVo.setPartyOrganizationActivitySerialNumber(secondLevelPartyOrganization.get("partyOrganizationName").toString());
                }else{
                    newsVo.setDataBelongPartyOrganizationSerialNumber("未知");
                }
            });
            Map<String, List<NewsVo>> collect = newsVos.stream()
                    .collect(Collectors.groupingBy(NewsVo::getPartyOrganizationActivitySerialNumber));

            List<String> sortedCategories = collect.entrySet().stream()
                    .sorted((e1, e2) -> (e2.getValue().size() - e1.getValue().size()))
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList());

            sortedCategories.forEach(name -> {
                collect.forEach((k, v) -> {
                    if (name.equals(k)) {
                        if (StringUtils.isNotBlank(k)) {
                            nameList.add(k);
                            cntList.add(v.size());
                        }
                    }
                });
            });
            List<JSONObject> treePartyOrganizationList = partyOrganizationMapper.getAllSecondLevelPartyOrganizationList();
            List<String> allOrgNameList = Lists.newArrayList();
            treePartyOrganizationList.forEach(organization -> {
                allOrgNameList.add(organization.get("partyOrganizationName").toString());
            });
            for (String s : allOrgNameList) {
                if (!nameList.contains(s)) {
                    nameList.add(s);
                    cntList.add(0);
                }
            }
            jsonObject.put("nameList", nameList);
            jsonObject.put("cntList", cntList);
        }
        return jsonObject;
    }

    @Override
    public JSONObject getMicroTwoContactTwoReportNewsList(String formatDate, String partyOrganizationSerialNumber, String partyOrganizationType, int pageNum, int pageSize, String search,int environment,String NewsTerminal) {
        // 输入筛选的党组织 树列表
        List<PartyOrganization> treePartyOrganizationList = Lists.newArrayList();
        PartyOrganization partyOrganization = partyOrganizationMapper.selectBySerialNumber(partyOrganizationSerialNumber);
        if (!ObjectUtils.isEmpty(partyOrganization)) {
            treePartyOrganizationList.add(partyOrganization);
        }
        List<PartyOrganization> partyOrganizations = partyOrganizationMapper.selectTreeListByParentSerialNumber(partyOrganizationSerialNumber, partyOrganizationType);
        if (!ObjectUtils.isEmpty(partyOrganizations)) {
            treePartyOrganizationList.addAll(partyOrganizations);
        }
        ArrayList<String> treePartyOrganizationSerialNumberList = Lists.newArrayList();
        treePartyOrganizationList.forEach(o1 -> {
            if (o1.getPartyOrganizationType().equals(partyOrganizationType)) {
                treePartyOrganizationSerialNumberList.add(o1.getPartyOrganizationSerialNumber());
            }
        });
        HashMap<String, Object> param = Maps.newHashMap();
        param.put("treePartyOrganizationSerialNumberList", treePartyOrganizationSerialNumberList);
        // 输入 筛选时间范围
        if (StringUtils.isNotBlank(formatDate)) {
            param.put("formatDate", formatDate);
        }
        List<String> activityTypeList = Lists.newArrayList();
        activityTypeList.add("双联系双报到");
        param.put("activityTypeList", activityTypeList);
        param.put("search", search);
        param.put("environment", environment);
        param.put("NewsTerminal", NewsTerminal);
        PageHelper.startPage(pageNum, pageSize);
        List<NewsVo> microTwoContactTwoReportNewsList = newsMapper.getMicroTwoContactTwoReportNewsList(param);
        execFormatSubTitle(microTwoContactTwoReportNewsList);
        PageInfo<NewsVo> pageInfo = new PageInfo<>(microTwoContactTwoReportNewsList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public List<NewsTags> getNewsTagsList() {
        return newsTagsMapper.getNewsTagsList();
    }

    @Override
    public List<NewsCategory> getNewsCategoryList(String newsTerminal) {
        List<NewsCategory> newsCategoryOneLevelList = newsCategoryMapper.getOneLevelCategory(newsTerminal );
        List<NewsCategory> resultList = Lists.newArrayList();
        for (NewsCategory newsCategory : newsCategoryOneLevelList) {
            List<NewsCategory> allList = newsCategoryMapper
                    .selectTreeListByParentSerialNumber(newsCategory.getNewsCategorySerialNumber(),newsTerminal );
            if (CollectionUtils.isEmpty(allList)) {
                resultList.add(newsCategory);
            } else {
                allList.add(newsCategory);
                resultList.add(buildTree(allList));
            }
        }

        List<NewsCategory> partyNewsCategoryList = newsCategoryMapper.getPartyNewsCategoryList();
        HashSet<NewsCategory> openNewsCategoryList = new HashSet<>();
       // 将 partyNewsCategoryList 从 resultList 中排除 并返回数组
        if (!ObjectUtils.isEmpty(partyNewsCategoryList)) {
            Set<String> partyNewsCategorySerialNumberSet = partyNewsCategoryList.stream().map(NewsCategory::getNewsCategorySerialNumber).collect(Collectors.toSet());

            for (NewsCategory nc : resultList) {
                if (StringUtils.isNotBlank(nc.getNewsCategorySerialNumber())) {
                    if (!partyNewsCategorySerialNumberSet.contains(nc.getNewsCategorySerialNumber())) {
                        openNewsCategoryList.add(nc);
                    }
                }
            }
        }
        return new ArrayList<>(openNewsCategoryList);
    }


    public static NewsCategory buildTree(List<NewsCategory> data) {
        Map<String, NewsCategory> nodeMap = new HashMap<>();
        NewsCategory root = null;

        // Step 1: Create all nodes and store them in a map
        for (NewsCategory row : data) {
            ;
            NewsCategory node = new NewsCategory(row.getNewsCategorySerialNumber(), row.getNewsCategory(), row.getRowStatus(), row.getParentSerialNumber(), row.getOperationID(), row.getOperationDatetime());
            nodeMap.put(row.getNewsCategorySerialNumber(), node);

            // Identify the root node (no parent)
            if (row.getParentSerialNumber() == null || row.getParentSerialNumber().isEmpty()) {
                root = node;
            }
        }

        // Step 2: Build the tree structure by linking parent and children
        for (NewsCategory row : data) {
            String serialNumber = ObjectUtils.isEmpty(row.getNewsCategorySerialNumber()) ? "" : row.getNewsCategorySerialNumber();
            String parentSerialNumber = ObjectUtils.isEmpty(row.getParentSerialNumber()) ? "" : row.getParentSerialNumber();

            if (parentSerialNumber != null && !parentSerialNumber.isEmpty()) {
                NewsCategory childNode = nodeMap.get(serialNumber);
                NewsCategory parentNode = nodeMap.get(parentSerialNumber);
                if (parentNode != null) {
                    if (childNode != null) {
                        parentNode.addChild(childNode);
                    }
                }
            }
        }

        return root;
    }

    @Override
    public List<JSONObject> getNoticePublish(String partyOrganizationSerialNumber, int pageNum, int pageSize,int environment,String NewsTerminal) {
        List<JSONObject> resultList = Lists.newArrayList();
        NewsCategory newsCategory = newsCategoryMapper.selectBySerialNumber("NC0000000000051");
        if (!ObjectUtils.isEmpty(newsCategory)) {
            List<String> treeList = Lists.newArrayList();
            treeList.add(newsCategory.getNewsCategorySerialNumber());
            List<NewsCategory> treeListByParentSerialNumber = newsCategoryMapper.selectTreeListByParentSerialNumber("NC0000000000051","");
            if (!ObjectUtils.isEmpty(treeListByParentSerialNumber)) {
                treeListByParentSerialNumber.forEach(nc -> {
                    treeList.add(nc.getNewsCategorySerialNumber());
                });
            }
            // 输入筛选的党组织 树列表
            List<String> treePartyOrganizationSerialNumberList =
                    Lists.newArrayList();
            List<PartyOrganization> treePartyOrganizationList = Lists.newArrayList();
            PartyOrganization partyOrganization = partyOrganizationMapper.selectBySerialNumber(partyOrganizationSerialNumber);
            if (!ObjectUtils.isEmpty(partyOrganization)) {
                treePartyOrganizationList.add(partyOrganization);
            }
            List<PartyOrganization> partyOrganizations = partyOrganizationMapper.selectTreeListByParentSerialNumber(partyOrganizationSerialNumber, "");
            if (!ObjectUtils.isEmpty(partyOrganizations)) {
                treePartyOrganizationList.addAll(partyOrganizations);
            }
            for (PartyOrganization organization : treePartyOrganizationList) {
                treePartyOrganizationSerialNumberList.add(organization.getPartyOrganizationSerialNumber());
            }
            PageHelper.startPage(pageNum, pageSize);
            List<NewsVo> newsVos = newsMapper.getNoticePublish(treeList, treePartyOrganizationSerialNumberList,environment,NewsTerminal);
            PageInfo<NewsVo> pageInfo = new PageInfo<>(newsVos);
            execFormatSubTitle(newsVos);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("category", newsCategory);
            jsonObject.put("news", pageInfo.getList());
            jsonObject.put("total", pageInfo.getTotal());
            resultList.add(jsonObject);
        }
        return resultList;
    }

    @Override
    public JSONObject searchContentList(int environment,String NewsTerminal) {
        JSONObject jsonObject = new JSONObject();
        List<NewsVo> dangJianZiXun = newsMapper.searchDangJianZiXunLimit(10,environment,NewsTerminal);
        List<Videos> yunShiDangKe = videosMapper.searchYunShiDangKeLimit(10,environment);
        List<Videos> hongSeGuanYing = videosMapper.searchHongSeGuanYingLimit(10,environment);
        List<StudyFiles> hongSeShuWu = studyFilesMapper.searchHongSeShuWuLimit(10,environment);
        jsonObject.put("党建资讯", dangJianZiXun);
        jsonObject.put("云视党课", yunShiDangKe);
        jsonObject.put("红色观影", hongSeGuanYing);
        jsonObject.put("红色书屋", hongSeShuWu);
        return jsonObject;
    }

    @Override
    public JSONObject getStudyAllDiscuss(String formatDate, String partyOrganizationSerialNumber,
                                         String partyOrganizationType,
                                         int pageNum, int pageSize, String search,int environment,String NewsTerminal) {
        // 输入筛选的党组织 树列表
        List<PartyOrganization> treePartyOrganizationList = Lists.newArrayList();
        PartyOrganization partyOrganization = partyOrganizationMapper.selectBySerialNumber(partyOrganizationSerialNumber);
        if (!ObjectUtils.isEmpty(partyOrganization)) {
            treePartyOrganizationList.add(partyOrganization);
        }
        List<PartyOrganization> partyOrganizations = partyOrganizationMapper.selectTreeListByParentSerialNumber(partyOrganizationSerialNumber, partyOrganizationType);
        if (!ObjectUtils.isEmpty(partyOrganizations)) {
            treePartyOrganizationList.addAll(partyOrganizations);
        }
        ArrayList<String> treePartyOrganizationSerialNumberList = Lists.newArrayList();
        treePartyOrganizationList.forEach(o1 -> {
            if (o1.getPartyOrganizationType().equals(partyOrganizationType)) {
                treePartyOrganizationSerialNumberList.add(o1.getPartyOrganizationSerialNumber());
            }
        });
        HashMap<String, Object> param = Maps.newHashMap();
        param.put("treePartyOrganizationSerialNumberList", treePartyOrganizationSerialNumberList);
        // 输入 筛选时间范围
        if (StringUtils.isNotBlank(formatDate)) {
            param.put("formatDate", formatDate);
        }
        param.put("search", search);
        param.put("environment", environment);
        param.put("NewsTerminal", NewsTerminal);
        PageHelper.startPage(pageNum, pageSize);
        List<NewsVo> microTwoContactTwoReportNewsList = newsMapper.getStudyAllDiscuss(param);
        execFormatSubTitle(microTwoContactTwoReportNewsList);
        PageInfo<NewsVo> pageInfo = new PageInfo<>(microTwoContactTwoReportNewsList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getDiscussDetailComments(String commentObjectSerialNumber,String commentType, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Comments> comments = commentsMapper.getDiscussDetailComments(commentObjectSerialNumber,commentType);
        PageInfo<Comments> pageInfo = new PageInfo<>(comments);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getStudyMyDiscuss(String userId,String commentType, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Comments> comments = commentsMapper.getStudyMyDiscuss(userId,commentType);
        PageInfo<Comments> pageInfo = new PageInfo<>(comments);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getAuditList(String search,
                                   String partyOrganizationSerialNumber,
                                   String auditStatus,
                                   List<String> activityTypeList,
                                   String partyOrganizationType,
                                   int pageNum,
                                   int pageSize,
                                   int environment,String NewsTerminal) {
        // 输入筛选的党组织 树列表
        List<PartyOrganization> treePartyOrganizationList = Lists.newArrayList();
        PartyOrganization partyOrganization = partyOrganizationMapper.selectBySerialNumber(partyOrganizationSerialNumber);
        if (!ObjectUtils.isEmpty(partyOrganization)) {
            treePartyOrganizationList.add(partyOrganization);
        }

        ArrayList<String> treePartyOrganizationSerialNumberList = Lists.newArrayList();
        treePartyOrganizationList.forEach(o1 -> {
            if (o1.getPartyOrganizationType().equals(partyOrganizationType)) {
                treePartyOrganizationSerialNumberList.add(o1.getPartyOrganizationSerialNumber());
            }
        });
        if(CollectionUtils.isEmpty(treePartyOrganizationSerialNumberList)){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list", Lists.newArrayList());
            jsonObject.put("total", 0);
            return jsonObject;
        }
        HashMap<String, Object> param = Maps.newHashMap();
        param.put("treePartyOrganizationSerialNumberList", treePartyOrganizationSerialNumberList);
        param.put("activityTypeList", activityTypeList);
        param.put("search", search);
        param.put("auditStatus", auditStatus);
        param.put("environment", environment);
        param.put("NewsTerminal", NewsTerminal);
        PageHelper.startPage(pageNum, pageSize);
        List<NewsVo> auditNewsList = newsMapper.getAuditList(param);
        PageInfo<NewsVo> pageInfo = new PageInfo<>(auditNewsList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public List<JSONObject> getMicroManagerPartyNewsList(String newsCategorySerialNumber, String phone, int pageNum, int pageSize, String search,int environment,String NewsTerminal) {
        List<JSONObject> resultList = Lists.newArrayList();

        // 如果没有传固定的分类id 则获取所有的分类的子节点
        if (StringUtils.isBlank(newsCategorySerialNumber)) {
            List<NewsCategory> oneLevelCategory = newsCategoryMapper.getOneLevelCategory(NewsTerminal);
            oneLevelCategory.forEach(newsCategory -> {
                List<String> treeList = Lists.newArrayList();
                treeList.add(newsCategory.getNewsCategorySerialNumber());
                List<NewsCategory> treeListByParentSerialNumber = newsCategoryMapper.selectTreeListByParentSerialNumber(newsCategory.getNewsCategorySerialNumber(),NewsTerminal);
                if (!ObjectUtils.isEmpty(treeListByParentSerialNumber)) {
                    treeListByParentSerialNumber.forEach(nc -> {
                        treeList.add(nc.getNewsCategorySerialNumber());
                    });
                }
                PageHelper.startPage(pageNum, pageSize);
                List<NewsVo> newsVos = newsMapper.getMicroManagerPartyNewsList(treeList, search,phone,environment,NewsTerminal);
                PageInfo<NewsVo> pageInfo = new PageInfo<>(newsVos);
                execFormatSubTitle(newsVos);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("category", newsCategory);
                jsonObject.put("news", pageInfo.getList());
                jsonObject.put("total", pageInfo.getTotal());
                resultList.add(jsonObject);
            });
        }
        // 如果传了固定的分类id 则获取该分类下的所有子节点
        else {
            NewsCategory newsCategory = newsCategoryMapper.selectBySerialNumber(newsCategorySerialNumber);
            if (!ObjectUtils.isEmpty(newsCategory)) {
                List<String> treeList = Lists.newArrayList();
                treeList.add(newsCategory.getNewsCategorySerialNumber());
                List<NewsCategory> treeListByParentSerialNumber = newsCategoryMapper.selectTreeListByParentSerialNumber(newsCategorySerialNumber,"");
                if (!ObjectUtils.isEmpty(treeListByParentSerialNumber)) {
                    treeListByParentSerialNumber.forEach(nc -> {
                        treeList.add(nc.getNewsCategorySerialNumber());
                    });
                }
                PageHelper.startPage(pageNum, pageSize);
                List<NewsVo> newsVos = newsMapper.getMicroManagerPartyNewsList(treeList, search,phone,environment,NewsTerminal);
                PageInfo<NewsVo> pageInfo = new PageInfo<>(newsVos);
                execFormatSubTitle(newsVos);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("category", newsCategory);
                jsonObject.put("news", pageInfo.getList());
                jsonObject.put("total", pageInfo.getTotal());
                resultList.add(jsonObject);
            }
        }
        return resultList;
    }

    @Override
    public JSONObject getAllListSearch(int pageNum, int pageSize, String search,int environment,String NewsTerminal) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> searchList =  newsMapper.getAllListSearch(search,environment,NewsTerminal);
        searchList.forEach(newsVo -> {
            String newsSubTitle = newsVo.getString("newsSubTitle");
            Document doc = Jsoup.parse(newsSubTitle);

            // 查找第一个<p>标签
            Elements paragraphs = doc.select("p");
            if (paragraphs.size() > 0) {
                Element firstParagraph = paragraphs.first(); // 获取第一个<p>标签
                String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                if (content.length() > 70) {
                    content = content.substring(0, 67) + "...";
                }
                newsVo.put("newsSubTitle",content);
                return;
            } else {
                Elements h1 = doc.select("h1");
                Elements h2 = doc.select("h2");
                Elements h3 = doc.select("h3");
                Elements h4 = doc.select("h4");
                Elements h5 = doc.select("h5");
                if (h1.size() > 0) {
                    Element firstParagraph = h1.first(); // 获取第一个<h1>标签
                    String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                    if (content.length() > 70) {
                        content = content.substring(0, 67) + "...";
                    }
                    newsVo.put("newsSubTitle",content);
                    return;
                }
                if (h2.size() > 0) {
                    Element firstParagraph = h2.first(); // 获取第一个<h2>标签
                    String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                    if (content.length() > 70) {
                        content = content.substring(0, 67) + "...";
                    }
                    newsVo.put("newsSubTitle",content);
                    return;
                }
                if (h3.size() > 0) {
                    Element firstParagraph = h3.first(); // 获取第一个<h1>标签
                    String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                    if (content.length() > 70) {
                        content = content.substring(0, 67) + "...";
                    }
                    newsVo.put("newsSubTitle",content);
                    return;
                }
                if (h4.size() > 0) {
                    Element firstParagraph = h4.first(); // 获取第一个<h1>标签
                    String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                    if (content.length() > 70) {
                        content = content.substring(0, 67) + "...";
                    }
                    newsVo.put("newsSubTitle",content);
                    return;
                }
                if (h5.size() > 0) {
                    Element firstParagraph = h5.first(); // 获取第一个<h1>标签
                    String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                    if (content.length() > 70) {
                        content = content.substring(0, 67) + "...";
                    }
                    newsVo.put("newsSubTitle",content);
                    return;
                }
            }
        });
        PageInfo<JSONObject> pageInfo = new PageInfo<>(searchList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("search", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getDetailSearch(String id, String searchType) {
        JSONObject jsonObject = new JSONObject();
        if("news".equals(searchType)){
            News news = newsMapper.selectByPrimaryKey(id);
            String newsViewsCount = news.getNewsViewsCount();
            int i;
            if (StringUtils.isNotBlank(newsViewsCount)) {
                i = Integer.parseInt(newsViewsCount);
                i += 1;
            } else {
                newsViewsCount = "0";
                i = Integer.parseInt(newsViewsCount);
                i += 1;
            }
            news.setNewsViewsCount(String.valueOf(i));
            newsMapper.updateNewsViewsCount(news);
            jsonObject = JSONObject.parseObject(JSONObject.toJSONString(news));
        }
        if("file".equals(searchType)){
            studyFilesMapper.addViewCount(id);
            StudyFiles studyFiles = studyFilesMapper.getStudyFilesDetail(id);
            jsonObject = JSONObject.parseObject(JSONObject.toJSONString(studyFiles));

        }
        if("video".equals(searchType)){
            videosMapper.addViewCount(id);
            Videos videosDetail = videosMapper.getVideosDetail(id);
            jsonObject = JSONObject.parseObject(JSONObject.toJSONString(videosDetail));

        }
        return jsonObject;
    }

    @Override
    public JSONObject getWorkTeamLogNewsList(String workTeamSerialNumber, String phone, String formatDate,String status, int pageNum, int pageSize,int environment,String NewsTerminal) {
        PageHelper.startPage(pageNum, pageSize);
        List<NewsVo> newsVos = newsMapper.getWorkTeamLogNewsList(workTeamSerialNumber, phone,formatDate,status,environment,NewsTerminal);

        PageInfo<NewsVo> pageInfo = new PageInfo<>(newsVos);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("news", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public List<JSONObject> getCarouselConfig() {
            return newsMapper.getCarouselConfig();
    }

    @Override
    public List<JSONObject> getCarouselConfigBigScreen() {
        return newsMapper.getCarouselConfigBigScreen();
    }

    @Override
    public JSONObject getLeaveWord(String userId, String commentReplyStatus, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> leaveWord = commentsMapper.getLeaveWord(userId,commentReplyStatus);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(leaveWord);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getLeaveWordDetail(String messageSerialNumber) {
       return commentsMapper. getPartyMemberCommentsDetail(messageSerialNumber);
    }

    @Override
    public List<NewsCategory> getPartyNewsCategoryList() {
        return newsCategoryMapper.getPartyNewsCategoryList();
    }

    @Override
    public List<JSONObject> getNewsTagsChengGuoList() {
        return newsMapper.getNewsTagsChengGuoList();
    }
}
